package com.augurit.wf.common.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.base.action.ExtBaseAction;
import com.augurit.common.base.extmodel.ExtResult;
import com.augurit.common.base.form.Attachment;
import com.augurit.common.sysfile.service.ISysFileService;
import com.augurit.common.sysfile.web.form.SysFileForm;
import com.augurit.common.util.FileUtils;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.common.constant.WfConstant;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "wf-attachment-mgmt.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/wf/app/fawen/EditZhengwenDoc.jsp"),
	@Result(name = CrudActionSupport.INPUT, location = "/wf/app/fawen/oa-fawen-input.jsp"),
	@Result(name = WfAttachmentMgmtAction.EDIT_DOUCMENT, location = "/wf/client/common/attachment-mgmt/edit-document.jsp"),
	@Result(name = WfAttachmentMgmtAction.READ_DOCUMENT, location = "/wf/client/common/attachment-mgmt/read-document.jsp"),
	@Result(name = WfAttachmentMgmtAction.MAKE_DOCUMENT, location = "/wf/client/common/attachment-mgmt/make-document.jsp")
})
public class WfAttachmentMgmtAction extends ExtBaseAction implements ModelDriven<SysFileForm>, Preparable{
	public final static String EDIT_DOUCMENT = "edit-document";		//编辑（或加载）正文
	public final static String READ_DOCUMENT = "read-document";		//查看正文
	public final static String MAKE_DOCUMENT = "make-document";		//发文制文
	
	public final static String WORD_FORMAT_FILE = "doc";	//WORD格式文件
	public final static String ATTACHMENT_TYPE = "0";		//附件类型
	public final static String DOCUMENT_TYPE = "1";			//正文类型
	public final static String MAKE_DOCUMENT_TYPE = "2";	//制文类型
	
	@Autowired
	private ISysFileService sysFileService;
	@Autowired
	private IWfBusTemplateService wfBusTemplateService;
	
	private Long sysFileId;		
	private Long[] sysFileIds;
	private SysFileForm form;
	
	
	/**
     * 显示所有的文档（包括正文和附件）
     * @return
     * @throws Exception
     */
    public String listAllDocuments() throws Exception {
		List<SysFileForm> list = sysFileService.getSortedFilesByBusObj(
				form.getEntity(), form.getEntityId(), "order by file.memo2 desc, file.cdt desc");

		if (list != null && list.size() > 0)
			ExtBaseAction.extRenderGridJson(list);
		else {
			list = new ArrayList<SysFileForm>(1);

			ExtResult extResult = new ExtResult();
			extResult.setResult(list);
			extResult.setTotalCount(0);
			extResult.setSuccess(true);

			Struts2Utils.renderJson(Struts2Utils.getJsonString(extResult));
		}
		return null;
	}
    
    /**
	 * 保存在线编辑的office文档
	 * 
	 * @return
	 * @throws Exception
	 */
    public String saveDocument() throws Exception{
    	List<Attachment> attachments = this.getAttachmentList();
    	if(attachments != null && attachments.size() == 1){
    		this.fillFileProperty(form);
    		
    		boolean success = this.upload(form, attachments.get(0));
        	
    		if(success)
    			ExtBaseAction.extRenderSuccess();
    		else
    			ExtBaseAction.extRenderFailture();
    	}
    	return null;
    }
    
    /**
     * 上传正文到服务器
     */
    public String uploadDocument() throws Exception{
    	List<Attachment> attachments = this.getAttachmentList();
    	if(attachments != null && attachments.size() == 1){
    		this.fillFileProperty(form);
    		
    		boolean success = this.upload(form, attachments.get(0));
    		
    		if(success)
        		renderHtml("{'success':true}");
    		else
    			renderHtml("{'success':false}");
    	}
    	return null;
    }
    
    /**
     * 从服务器端读取附件
     * @return
     * @throws Exception
     */
    private File readFileFromServer() throws Exception{
		//根路径
    	String directoryPath = BaseAction.getApplication().getRealPath("/");
    	//模板文件存放的绝对路径
    	String filePath = directoryPath + form.getFilePath();
    	return FileUtils.openFile(filePath, form.getFileCode()+"."+form.getFileFormat(), true, directoryPath, true, false);
    }
    
    /**
     * 读取空白文档
     * @return
     * @throws Exception
     */
    private File readBlankFile() throws Exception{
    	//根路径
    	String directoryPath = BaseAction.getApplication().getRealPath("/");
    	//模板文件存放的绝对路径
    	String filePath = directoryPath + "/wf/bi/bus-template/blank-template/blank.doc";
    	return new File(filePath);
    }
    
    /**
     * 下载
     * @param file
     * @throws Exception
     */
    private void download(File file) throws Exception{
    	InputStream in = null;
    	ServletOutputStream out = null;
         	
         //重置response
    	BaseAction.getResponse().reset();
    	BaseAction.getResponse().setContentType("application/octet-stream");
    	if(form.getFileName() != null){
    		String fileName = FileUtils.reEncodeChineseFileName(form.getFileName(), BaseAction.getRequest());
        	BaseAction.getResponse().setHeader("Content-Disposition","attachment; filename=" + fileName);
    	}

    	in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
    	out = BaseAction.getResponse().getOutputStream();
        FileUtils.copy(in, out);  
         
    }
    
    private boolean isFileExist(){
    	return sysFileId != null;
    }
    
    private void fillFileProperty(SysFileForm form){
    	form.setFileCode(String.valueOf(new Date().getTime()));
    	form.setFilePath(getDefaultFilePath(form));
    }
    
    private String getDefaultFilePath(SysFileForm form){
    	if(form != null && form.getEntityId() != null)
    		return WfConstant.FILE_UPLOAD_PATH + form.getEntity() + "#" + form.getEntityId();
    	else
    		return WfConstant.FILE_UPLOAD_PATH;
    }
    
    /**
     * 读取文档
     * @return
     * @throws Exception
     */
    public String readDocument() throws Exception {
    	
    	File file = null;
    	if(isFileExist()){
    		file = readFileFromServer();
    	}
    	else{
    		file = readBlankFile();
    	}
    	download(file);
    	return null;
    }
    
    /**
     * 新增或者编辑正文
     * @throws Exception
     */
    public String editDocument()throws Exception {
    	return EDIT_DOUCMENT;
    }
    
    public String readOnlyDocument() throws Exception {
    	return READ_DOCUMENT;
    }
    
    /**
     * 制文
     */
    public String makeDocument() throws Exception {
    	if(form != null && form.getTemplateCode() != null && form.getTemplateCode().trim().length() > 0
    			&& form.getEntity() != null && form.getEntity().trim().length() > 0 && form.getEntityId() != null){
    		
    		//获取套打模板路径
    		String printTemplatePath = wfBusTemplateService.getPrintTemplatePath(form.getTemplateCode());
        	form.setPrintTplPath(printTemplatePath);

        	//获取正文文件路径
        	List<SysFileForm> list = sysFileService.getSortedFilesByBusObjAndType(form.getEntity(), form.getEntityId(), "ZHENGWEN", "order by file.memo2 desc, file.cdt desc");
        	if(list != null && list.size() > 0){
        		form.setZhengwenPath(list.get(0).getFilePath() + "/" + list.get(0).getFileCode() + ".doc");
        	}
    	}
    	return MAKE_DOCUMENT;
    }
    
    /**
     * 上传附件
     * @return
     * @throws Exception
     */
    public String uploadAttachment() throws Exception {
    	try{
    		List<Attachment> attachments = this.getAttachmentList();
        	if(attachments != null && attachments.size() > 0){
        		for(Attachment attachment:attachments){
        	    	
        			form.setFileType(ATTACHMENT_TYPE);
        			form.setFileName(attachment.getFileFileName());
        			this.upload(form.getEntity(), form.getEntityId(), form.getFilePath(), null, null, null, attachment);
        		}
        	}
        	this.renderText("successed");
    	}
    	catch(Exception e){
    		e.printStackTrace();
    	}
    	return null;
    }
    
    /**
     * 删除附件
     * @return
     * @throws Exception
     */
    public String deleteAttachment() throws Exception {
    	if(sysFileIds != null && sysFileIds.length > 0){
    		for(Long fileId:sysFileIds)
    			this.delete(fileId);
    	}
    	ExtBaseAction.extRenderSuccess();
    	return null;
    }
    
    /**
     * 实现ModelDriven模型驱动接口
     */
    public SysFileForm getModel() {
		return form;
	}

    /**
     * 实现Preparable接口
     * @throws Exception
     */
	public void prepare() throws Exception {
		if(sysFileId != null)
			form = sysFileService.get(sysFileId);
		else
			form = new SysFileForm();
	}
    
	/***************************************************
	 * get和set方法
	 ***************************************************/
	public Long getSysFileId() {
		return sysFileId;
	}

	public void setSysFileId(Long sysFileId) {
		this.sysFileId = sysFileId;
	}

	public Long[] getSysFileIds() {
		return sysFileIds;
	}

	public void setSysFileIds(Long[] sysFileIds) {
		this.sysFileIds = sysFileIds;
	}
}
